package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// GroupBuyOrderController 团购订单控制器
type GroupBuyOrderController struct {
	web.Controller
}

// List 获取团购订单列表
func (c *GroupBuyOrderController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	orderNo := c.GetString("order_no")
	activityName := c.GetString("activity_name")
	username := c.GetString("username")
	status, _ := c.GetInt8("status", -1)
	groupStatus, _ := c.GetInt8("group_status", -1)
	startTime := c.GetString("startTime")
	endTime := c.GetString("endTime")

	// 构建过滤条件
	filters := make(map[string]interface{})
	if orderNo != "" {
		filters["order_no"] = orderNo
	}
	if activityName != "" {
		filters["activity_name"] = activityName
	}
	if username != "" {
		filters["username"] = username
	}
	if status >= 0 {
		filters["status"] = status
	}
	if groupStatus >= 0 {
		filters["group_status"] = groupStatus
	}
	if startTime != "" {
		t, _ := time.Parse("2006-01-02 15:04:05", startTime)
		filters["start_time"] = t.Unix()
	}
	if endTime != "" {
		t, _ := time.Parse("2006-01-02 15:04:05", endTime)
		filters["end_time"] = t.Unix()
	}

	// 加盟商权限过滤
	if permResult.Admin.FranchiseId > 0 {
		// 非超级管理员，只能查看自己加盟商的订单
		filters["franchise_ids"] = []int64{permResult.Admin.FranchiseId}
	}

	// 查询订单列表
	orders, total, err := models.GetGroupBuyOrderList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购订单列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购订单列表成功",
		"data": map[string]interface{}{
			"list":  orders,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取团购订单详情
func (c *GroupBuyOrderController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取订单ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的订单ID",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetGroupBuyOrderById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购订单详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && order.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问此团购订单",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取团购订单详情成功",
		"data":    order,
	}
	c.ServeJSON()
}

// Audit 审核团购订单
func (c *GroupBuyOrderController) Audit() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		Id     int64  `json:"id"`
		Status int8   `json:"status"`
		Remark string `json:"remark"`
	}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetGroupBuyOrderById(req.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购订单详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && order.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权审核此团购订单",
		}
		c.ServeJSON()
		return
	}

	// 审核订单
	err = models.AuditGroupBuyOrder(req.Id, req.Status, req.Remark, permResult.Admin.Username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "审核订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "审核订单成功",
	}
	c.ServeJSON()
}

// Cancel 取消团购订单
func (c *GroupBuyOrderController) Cancel() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		Id int64 `json:"id"`
	}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取订单详情
	order, err := models.GetGroupBuyOrderById(req.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取团购订单详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 验证加盟商权限
	if permResult.Admin.FranchiseId > 0 && order.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权取消此团购订单",
		}
		c.ServeJSON()
		return
	}

	// 取消订单
	err = models.CancelGroupBuyOrder(req.Id, permResult.Admin.Username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "取消订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "取消订单成功",
	}
	c.ServeJSON()
}
